package cn.tb.system.service.impl;

import cn.tb.system.domain.Menu;
import cn.tb.system.mapper.MenuMapper;
import cn.tb.system.service.IMenuService;
import cn.tb.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tangbo
 * @since 2022-06-22
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> tree() {
        //一次性查询到所有的数据，放在缓存中
        List<Menu> menus = menuMapper.loadAll();
        Map<Long, Menu> allMenus = new HashMap<>();
        for (Menu menu : menus) {
            allMenus.put(menu.getId(),menu);
        }
        List<Menu> firstMenus = new ArrayList<>();
        for (Menu temp : menus) {
            if(temp.getParentId()==null){
                //顶级
                firstMenus.add(temp);
            }else {
                //不是顶级，找到自己的上级，把自己交给上级的children
                Menu parent = allMenus.get(temp.getParentId());
                parent.getChildren().add(temp);
            }
        }
        return firstMenus;
    }
}
